import React, { useEffect, useRef, useState } from 'react'
import { PageHeader, Modal, Steps, Button, Form, Input, Select, message, notification, TreeSelect, Upload } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import NewsEditor from '../../../components/news-manage/NewsEditor'
import style from './News.module.css'
import { classify, articleClassify, contentArticle, updateArticle, upload, uploadList } from "../../../api/api"
import Cropper from "react-cropper";
import "cropperjs/dist/cropper.css";
const { Step } = Steps;
const { Option } = Select;
const { TreeNode } = TreeSelect;
const { TextArea } = Input;


export default function NewsUpdate(props) {


  const [value, setValue] = useState();//分类选择树
  const [current, setCurrent] = useState(0)
  const [classifyList, setClassifyList] = useState([])
  const [categoriesList, setCategoriesList] = useState([])
  const [formInfo, setFormInfo] = useState({})
  const [content, setContent] = useState("")
  const [introduce, setIntroduce] = useState('')//介绍
  const [netdisk, setNetdisk] = useState([])//会员网盘链接
  const NewsForm = useRef(null)
  // const User = JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    const httpRequest = async () => {
      //获取分类列表
      const res1 = await classify()
      setClassifyList(res1.data.data)
      //获取文章内容类别分类信息
      const res2 = await articleClassify()
      setCategoriesList(res2.data.data)
      //获取文章内容
      const res3 = await contentArticle({
        articleId: props.match.params.id
      })
      // console.log(res3.data.data[0]);
      NewsForm.current.setFieldsValue({
        title: res3.data.data[0].title,
        classifyArrPath: res3.data.data[0].classifyArrPath.split(','),
        articleClassifyId: res3.data.data[0].articleClassifyId,
        imgUrl: res3.data.data[0].imgUrl
      })
      // console.log(res3.data.data[0].vipContent.split(','));
      setIntroduce(res3.data.data[0].introduce)
      setNetdisk(res3.data.data[0].vipContent.split(','))
      setImgUrl(res3.data.data[0].imgHost + res3.data.data[0].imgUrl)
      if (res3.data.data[0].articleClassifyId === 3) {
        setContent(res3.data.data[0].content)
      } else {
        let imgNameArr = res3.data.data[0].content.split(',');
        let imgUrlArr = []
        for (let i = 0; i < imgNameArr.length; i++) {
          imgUrlArr.push(res3.data.data[0].imgHost + imgNameArr[i])
        }
        setImgUrlList(imgUrlArr)
        setImgNameList(res3.data.data[0].content.split(','))
      }
    }
    httpRequest()
  }, [props.match.params.id])
  const handleNext = () => {
    if (current === 0) {
      NewsForm.current.validateFields().then(value => {
        // console.log(value);
        setFormInfo(value)
        setCurrent(current + 1)
      }).catch(error => {
        console.log(error);
      })
    } else {
      if (imgUrlList?.length > 0 && formInfo.articleClassifyId !== 3) {
        setCurrent(current + 1)
      } else if ((content === "" || content.trim() === "<p><br></p>")) {
        message.error('文章内容不能为空！');
      } else {
        setCurrent(current + 1)
      }

    }
  }
  const handlePrevious = () => {
    setCurrent(current - 1)
  }
  const handleSave = (auditState) => {
    // console.log(formInfo);
    updateArticle({
      ...formInfo,
      vipContent: (netdisk[0]?.trim().length > 0 && netdisk[1]?.trim().length > 0) ? netdisk : [],
      id: props.match.params.id,
      introduce,
      "content": formInfo.articleClassifyId === 3 ? content : imgNameList,
      "auditState": auditState,//审核状态
    })
    props.history.push(auditState === 0 ? "/news-manage/draft" : "/audit-manage/list");
    notification.info({
      message: '通知',
      description: `您可以到${auditState === 0 ? '草稿箱' : '审核列表'}中查看您的新闻`,
      placement: "bottomRight",
    });
  }
  //分类选择树
  const onChange = (newValue) => {
    // console.log(newValue);
    setValue(newValue);
  };


  //文章封面上传
  const [fileList, setFileList] = useState([]);
  const [imgUrl, setImgUrl] = useState();
  const [imgSrc, setImgSrc] = useState();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const cropperRef = useRef(null);

  const base64toFile = (dataurl, filename) => {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime
    })
  }

  const handleOk = async () => {
    const imageElement = cropperRef?.current;
    const cropper = imageElement?.cropper;
    setImgUrl(cropper.getCroppedCanvas().toDataURL())
    let file = base64toFile(cropper.getCroppedCanvas().toDataURL(), 'cover') //这个file就是base64转成的file文件
    let formData = new FormData();
    formData.append('file', file);
    const res = await upload(formData)
    if (res.data.code !== 200) return message.error('文件上传错误！');
    setImgUrl(res.data.data.imgHost + res.data.data.imgUrl)
    NewsForm.current.setFieldsValue({
      imgUrl: res.data.data.imgUrl
    })
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onImgFilesChange = async (file) => {
    const reader = new FileReader()
    //开始读文件
    //readAsDataURL: dataurl它的本质就是图片的二进制数据， 进行base64加密后形成的一个字符串，
    reader.readAsDataURL(file.file)
    // 成功和失败返回对应的信息，reader.result一个base64，可以直接使用
    reader.onload = () => {
      setImgSrc(reader.result)
    }
    setIsModalOpen(true);
    // onChangeImg({ file })
  };

  //文件列表上传
  const [imgUrlList, setImgUrlList] = useState([]);
  const [imgNameList, setImgNameList] = useState([])
  const fileRef = useRef(null)
  const changeList = async () => {
    // console.log(fileRef.current.files)
    let fileUrlArr = [];
    let fileNameArr = [];
    for (let i = 0; i < fileRef.current.files.length; i++) {
      let formData = new FormData();
      formData.append('isCreateMkdir', i);
      formData.append('file', fileRef.current.files[i]);
      //获取上传图片列表信息
      const res = await uploadList(formData)
      if (res.data.code !== 200) return message.error('文件上传错误！');
      fileUrlArr.push(res.data.data.imgHost + res.data.data.imgUrl)
      fileNameArr.push(res.data.data.imgUrl)
    }
    setImgUrlList(fileUrlArr)
    setImgNameList(fileNameArr)
  }

  return (
    <div>
      <PageHeader
        className="site-page-header"
        title="撰写文章"
      />
      <Steps current={current}>
        <Step title="基本信息" description="文章标题，文章分类" />
        <Step title="文章内容" description="文章主体内容" />
        <Step title="文章提交" description="保存草稿或者提交审核" />
      </Steps>

      <div style={{ marginTop: "50px" }}>
        <Form
          name="basic"
          labelCol={{
            span: 3,
          }}
          wrapperCol={{
            span: 21,
          }}
          className={current === 0 ? '' : style.active}
          ref={NewsForm}
        >
          <Form.Item
            label="文章标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入文章标题!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="文章分类"
            name="classifyArrPath"
            rules={[
              {
                required: true,
                message: '请选择文章分类!',
              },
            ]}
          >
            <TreeSelect
              showSearch
              style={{
                width: '100%',
              }}
              value={value}
              dropdownStyle={{
                maxHeight: 400,
                overflow: 'auto',
              }}
              placeholder="请选择文章分类"
              allowClear
              multiple
              treeDefaultExpandAll
              onChange={onChange}
            >
              {
                classifyList.map(item => <TreeNode value={item.path} title={item.title} key={item.path} disabled={item.children?.length > 0 || item.path === '/'}>
                  {
                    item.children.map(citem => <TreeNode value={citem.path} title={citem.title} key={citem.path} disabled={citem.children?.length > 0}>
                      {citem.children.map(ccitem => <TreeNode value={ccitem.path} title={ccitem.title} key={ccitem.path} disabled={ccitem.children?.length > 0}></TreeNode>)}
                    </TreeNode>)
                  }
                </TreeNode>)
              }
            </TreeSelect>
          </Form.Item>
          <Form.Item
            label="内容类别"
            name="articleClassifyId"
            rules={[
              {
                required: true,
                message: '请选择内容类别!',
              },
            ]}
          >
            <Select
            >
              {
                categoriesList.map(item => <Option value={item.id} key={item.id}>{item.title}</Option>)
              }

            </Select>
          </Form.Item>
          <Form.Item
            label="封面图片"
            name="imgUrl"
            rules={[
              {
                required: true,
                message: '请上传封面图片!',
              },
            ]}
          >
            <Upload
              customRequest={onImgFilesChange}
              listType="picture-card"
              maxCount={1}
              fileList={fileList}
            >
              <img
                alt=""
                style={{
                  width: imgUrl ? '100%' : '0%',
                }}
                src={imgUrl}
              />

              {imgUrl ? '' : '+ Upload'}
            </Upload>
            <Modal title="封面图片" open={isModalOpen} onCancel={handleCancel} maskClosable={false} footer={[
              <Button key="submit" type="primary" onClick={handleOk}>
                应用
              </Button>,
              <Button key="back" onClick={handleCancel}>
                取消
              </Button>,
            ]}>
              <Cropper
                src={imgSrc}
                style={{ height: 300, width: 480 }}
                // Cropper.js options
                initialAspectRatio={480 / 300}
                guides={false}
                // crop={onCrop}
                ref={cropperRef}
                viewMode={1}
                dragMode='move'
                cropBoxResizable={false}
              />
            </Modal>
          </Form.Item>
        </Form>
        <div className={current === 1 ? '' : style.active} style={{
          marginBottom: '10px'
        }}>简介：
          <TextArea
            value={introduce}
            // showCount
            // maxLength={100}
            style={{
              height: 60,
            }}
            onChange={(e) => {
              // console.log('Change:', e.target.value);
              setIntroduce(e.target.value)
            }}
          />
        </div>
        <div className={current === 1 ? '' : style.active} style={{ display: formInfo.articleClassifyId === 3 ? '' : 'none' }}>
          <NewsEditor getContent={(value) => {
            // console.log(value);
            setContent(value)
          }} content={content}></NewsEditor>
        </div>
        <div className={current === 1 ? '' : style.active} style={{ display: formInfo.articleClassifyId !== 3 ? '' : 'none' }}>
          <Button type="primary" icon={<DownloadOutlined />} size='large' onClick={() => {
            document.querySelector('.file-input').click()
          }}>上传图片文件夹</Button><span style={{ display: imgUrlList?.length ? '' : 'none', marginLeft: '10px' }}>已上传{imgUrlList?.length}个文件</span>
          <input ref={fileRef} title="" type='file' name="file" webkitdirectory="webkitdirectory" className="file-input" onChange={changeList} style={{
            display: "none"
          }} />
          <div style={{
            border: '1px solid #1890ff',
            height: '500px',
            overflow: 'auto',
            marginTop: '20px'
          }}>
            {
              formInfo.articleClassifyId === 1 && imgUrlList.map((item) => {
                return <img
                  alt=""
                  style={{
                    width: '100%'
                  }}
                  src={item}
                  key={item}
                />
              })
            }
            {
              formInfo.articleClassifyId === 2 && imgUrlList.map((item) => {
                return <img
                  alt=""
                  style={{
                    width: '50%'
                  }}
                  src={item}
                  key={item}
                />
              })
            }
          </div>
        </div>
        <div className={current === 1 ? '' : style.active} style={{
          marginTop: '20px'
        }}>会员资源
          <Input placeholder="网盘链接" value={netdisk[0]} onChange={(e) => setNetdisk([e.target.value, netdisk[1]])} style={{
            marginLeft: 20,
            width: 300,
          }} />
          <Input placeholder="验证码" value={netdisk[1]} onChange={(e) => setNetdisk([netdisk[0], e.target.value])} style={{
            width: 100,
          }} /></div>
      </div>

      <div style={{ marginTop: "50px" }}>
        {
          current === 2 && <span>
            <Button type="primary" onClick={() => handleSave(0)}>保存草稿箱</Button>
            <Button danger onClick={() => handleSave(1)}>提交审核</Button>
          </span>
        }
        {
          current < 2 && <Button type="primary" onClick={() => handleNext()}>下一页</Button>
        }
        {
          current > 0 && <Button onClick={() => handlePrevious()}>上一页</Button>
        }

      </div>
    </div>
  )
}
